import Taro, {Component} from '@tarojs/taro'
import {View, Image, Text, RichText} from '@tarojs/components'
import {observer, inject} from '@tarojs/mobx'
import {IStoreProps} from '../../store/Stores'
import {SignOutput} from '../../api/api'

import './sign.scss'
import bg_16 from '../../assets/img/bg_16.png'
import icon_82 from '../../assets/img/icon_82.png'
import {articleType, showToast} from "../../utils/common";

interface signItem {
  signDate: string,
  signPoint: string,
  isSign: boolean
}

interface IHomeProps extends IStoreProps {
}

@inject("stores")
@observer
class Sign extends Component<IHomeProps> {

  state = {
    isShow: false, // 控制签到弹窗
    isRule: false, // 控制规则弹窗
    signNums: 0, // 连续签到天数
    signItems: [] as signItem[], // 签到日期
    signRecord: {} as SignOutput,
    signTime: '', // 签到时间
    todayIsSign: false, // 今天是否已签到
    singRule: {} // 签到规则
  }

  componentWillMount() {
    this.getSignItems()
    this.getSignRecord()
  }

  componentDidShow(): void {
    this.getSignRule()
  }

  /**
   * 生成签到时间表
   * @param offset 已签到天数
   */
  getSignItems(offset: number = 0) {
    let paramOffset = offset
    if(offset !== 0) { offset -= 1 }
    let temp = Array(7).fill(0)
    let sub: signItem = {}
    let signItems = temp.map((item, index) => {
      sub = {
        signDate: this.getDay(index - offset), // 签到日期
        signPoint: '+5', // 签到奖励
      }
      if(index < paramOffset) {
        // 已签到的天数
        sub.isSign = true
      }
      else {
        // 未签到天数
        sub.isSign = false
      }
      return sub
    })
    this.setState({signItems})
  }

  getSignRecord = () => {
    let offset = 0
    let {userStore} = this.props.stores
    userStore.getUserSignRecordAsync({
      callback: res => {
        let signNums = res.signDays || 0
        console.log(signNums)
        if(signNums > 0) {
          // 有连续签到天数时, 处理签到时间表
          if(signNums <= 7) { offset = signNums }
          else { offset = signNums % 7 }
          this.getSignItems(offset)
        }
        this.setState({
          signRecord: res,
          signTime: res.signTime,
          signNums,
          todayIsSign: res.isTodaySign
        })
      }
    })
  }

  /**
   * 签到 更新签到时间、连续签到天数
   */
  sign = () => {
    let {signRecord} = this.state
    if (signRecord.isTodaySign) {
      showToast('您今天已经签过了,明天继续来哦~');
      return
    }
    let {userStore} = this.props.stores
    userStore.signAsync({
      callback: res => {
        this.setState({
          signTime: res.signTime,
          isShow: true,
          signNums: res.signDays,
          todayIsSign: res.isTodaySign
        }, () => this.getSignRecord())
      }
    })
  }

  // 获取几天前或几天后的年月日
  getDay = (num: number) => {
    let now = new Date()
    let nowTime = now.getTime() // 时间戳，毫秒
    now.setTime(24 * 60 * 60 * 1000 * num + nowTime)
    let month: any = now.getMonth() + 1
    let day: any = now.getDate()
    if (month < 10) {
      month = '0' + month
    }
    if (day < 10) {
      day = '0' + day
    }
    if (num === 0) return '今天'
    return `${month}.${day}`
  }

  setShow = (field: string) => {
    console.log(field)
    this.setState({[field]: !this.state[field]})
  }

  getSignRule() {
    const id = articleType.signRule
    let { dynamicStore } = this.props.stores
    dynamicStore.getArticleDetail({
      form: { id },
      callback: res => {
        this.setState({ singRule: res.artContent })
      }
    })
  }

  render() {
    let {isShow, isRule, signItems, todayIsSign, signNums, singRule} = this.state
    return (
      <View className='sign page-bg'>
        <View className='sign-header'>
          <Image className='sign-header__bg' src={require('../../assets/img/bg_02.png')}/>
          <View className='sign-header__line'>
            <View className='sign-header__lx'>已连续签到 <Text className='sign-header__day'>{signNums} </Text>天</View>
            <View className='sign-header__rule icon-link-theme' onClick={this.setShow.bind(this, 'isRule')}>规则介绍</View>
          </View>
          <View className='sign-header__line2'>
            {
              signItems.map(item => {
                return (
                  <View className='sign-header__item'>
                    <View className={item.isSign ? 'sign-header__point sign-header__pointed' : 'sign-header__point'}>{!item.isSign&&item.signPoint}</View>
                    <View className={item.signDate==='今天'?'color-orange':''}>{item.signDate}</View>
                  </View>
                )
              })
            }

            {/* <View className='sign-header__item'>
              <View className='sign-header__point sign-header__pointed' />
              <View>12.28</View>
            </View>
            <View className='sign-header__item'>
              <View className='sign-header__point sign-header__pointed' />
              <View className='color-orange'>今天</View>
            </View>*/}
          </View>
        </View>
        {
          todayIsSign && <View className='sign-btn'>今天已签到</View>
        }
        {
          !todayIsSign && <View className='sign-btn' onClick={this.sign.bind(this)}>点击签到</View>
        }
        <View className='item-op' style={{display: 'none'}}>
          <View className='item-op__item'>
            <View className='item-op_l'>
              <View className='item-op__title'>每日签到</View>
              <View className='item-op__desc'>每日签到可领取对应现金奖励</View>
            </View>
            <View className='item-op__r bg-line'>
              去完成
            </View>
          </View>

          <View className='item-op__item'>
            <View className='item-op_l'>
              <View className='item-op__title'>注册成功 <Text className='color-orange'>+1元</Text></View>
              <View className='item-op__desc'>成功注册平台可领取现金奖励</View>
            </View>
            <View className='item-op__r bg-line-qu'>
              领取奖励
            </View>
          </View>

          <View className='item-op__item'>
            <View className='item-op_l'>
              <View className='item-op__title'>邀请好友 <Text className='color-orange'>+1元</Text></View>
              <View className='item-op__desc'>成功好友注册可领取现金奖励</View>
            </View>
            <View className='item-op__r bg-line'>
              去完成
            </View>
          </View>

          <View className='item-op__item'>
            <View className='item-op_l'>
              <View className='item-op__title'>平台首次消费 <Text className='color-orange'>+1元</Text></View>
              <View className='item-op__desc'>首次在平台消费可领取现金奖励</View>
            </View>
            <View className='item-op__r bg-line-ing'>
              进行中
            </View>
          </View>
        </View>

        <View className={isShow ? 'sign-success sign-show' : 'sign-success'}
              onClick={this.setShow.bind(this, 'isShow')}>
          <View className='sign-success-content'>
            <Image src={bg_16} className='success-bg'/>
            <View className='info'>
              <View className='title'>打卡成功</View>
              <View className='integral'><Text className='count'>+5 </Text>积分</View>
              <View className='desc'>打卡成功,明天继续来哦~</View>
            </View>
            <Image src={icon_82} className='btn-close' onClick={this.setShow.bind(this, 'isShow')} />
          </View>
        </View>

        <View className={isRule ? 'sign-success sign-show' : 'sign-success'}
              onClick={this.setShow.bind(this, 'isRule')} >
          <View className='sign-success-content'>
            <View className='info-text'>
              <View className='rule-title'>—— 规则介绍 ——</View>
              <View className='rule-desc rich-text'>
               <RichText nodes={singRule} />
              </View>
            </View>
            <Image src={icon_82} className='btn-close' onClick={this.setShow.bind(this, 'isRule')} />
          </View>
        </View>
      </View>
    )
  }
}

export default Sign
